<template>
  <div>
    <group title="做题卡类型及绑定">
      <selector
        title="工种"
        :options="workTypeVK"
        v-model="workTypeId"
        placeholder="选择做题的工种"
      ></selector>
      <selector
        title="类型"
        :options="workCardVK"
        v-model="cardTypeId"
        placeholder="选择做题卡类型"
      >
      </selector>

      <group title="做题卡详情">
        <loading v-model="isLoading"></loading>
        <!-- 月卡内容 -->
        <template v-if="cardTypeId === monthCardInfo.cardType">
          <cell 
            :title="expireTitle" 
            :value="expandExpire"
            >
            <inline-loading v-if="!monthCardInfo.period"></inline-loading>
          </cell>
          <cell 
            title="价格" 
            :value="monthRealPrice | formatMoney"
            >
            <inline-loading v-if="!monthCardInfo.price"></inline-loading>
          </cell>
          <group title="购卡说明">
            <p class="payMsg">
              包月卡有效期为{{monthCardInfo.period}}日，有效期内只能做绑定工种的练习题，做题练习次数不限，超期作废。请确认您选择的工种，购买成功后不接受任何理由的退款。
            </p>
          </group>
        </template>
        <!-- 次卡内容 -->
        <template v-if="cardTypeId === onceCardInfo.cardType">
          <x-number 
          title="次数" 
          :value="number"
          :min="1" 
          @on-change="getTotalMoney"
          v-model="number"
          >
            <inline-loading v-if="!number"></inline-loading>
          </x-number>

          <cell 
          title="单价：" 
          :value="onceCardInfo.price | formatMoney"
          >
            <inline-loading v-if="!onceCardInfo.price"></inline-loading>
          </cell>

          <cell 
          title="合计：" 
          :value="totalMoney | formatMoney"
          >
            <inline-loading v-if="!totalMoney"></inline-loading>
          </cell>

          <group title="购卡说明">
            <p class="payMsg">
              次卡有效期为{{onceCardInfo.period}}日，有效期内只能做绑定工种的练习题，次数由购买次数决定，超期作废。请确认您选择的工种，购买成功后不接受任何理由的退款。
            </p>
          </group>
        </template>
      </group>  
      <div class="payButton">
        <x-button type="primary" @click.native="payment">购买</x-button>
      </div>
    </group>
  </div>
</template>
<script>
import {
  XNumber,
  Panel,
  Group,
  Selector,
  XButton,
  Cell,
  Msg,
  Loading,
  InlineLoading,
  dateFormat
} from 'vux'
import { mapGetters, mapActions } from 'vuex'
export default {
  name: 'SelectCard',
  components: {
    XNumber,
    Panel,
    Group,
    Selector,
    XButton,
    Cell,
    Msg,
    Loading,
    InlineLoading,
    dateFormat
  },
  data () {
    return {
      number: 1, // 次数
      totalMoney: 2, // 支付总金额
      appendShow: true,
      workTypeId: 10061001, // 工种编号的绑定变量
      cardTypeId: 10011001, // 卡类型的编号的绑定变量
      expireTitle: ''       // 月卡有效期的title
    }
  },
  mounted () {
    // 获取路由来的工种信息
    if (this.$route.params.workid !== undefined) {
      this.workTypeId = this.$route.params.workid
    }
    if (this.$route.params.cardId !== undefined) {
      this.cardTypeId = this.$route.params.cardId
    }
  },
  computed: {
    ...mapGetters(['appUserInfo', 'agencyList', 'onceCardInfo', 'monthCardInfo', 'workCardVK', 'workTypeVK', 'allCardInfo']),

    isLoading: function () {
      if (this.workCardVK !== undefined) {
        return false
      } else {
        return true
      }
    },
    // 用户是否有当前工种的月卡，有则返回有效期
    hadCardExpire: function () {
      var userAllCard = this.allCardInfo
      for (var i = 0; i < userAllCard.length; i++) {
        if (userAllCard[i].workType === this.workTypeId && userAllCard[i].cardType === this.cardTypeId) {
          return userAllCard[i].expireDate
        }
      }
    },
    expandExpire: function () {
      var moment = require('moment')
      var startTimestamp = ''
      if (this.hadCardExpire) {
        startTimestamp = moment(this.hadCardExpire)
        this.expireTitle = '续费有效期'
      } else {
        this.expireTitle = '有效期'
        startTimestamp = moment()
      }
      return moment(startTimestamp).add(1, 'month').format('YYYY-MM-DD HH:mm:ss')
    },

    discountPrice: function () {
      var userinfo = this.appUserInfo
      var alist = this.agencyList
      for (var i = 0; i < alist.length; i++) {
        if (alist[i].agencyCode === userinfo.agencyCode) {
          return alist[i].discount
        }
      }
    },
    monthRealPrice: function () {
      var discount = this.discountPrice
      console.log('计算价格')
      console.log(discount)
      console.log('月卡价格')
      console.log(this.monthCardInfo.price)
      if (discount === undefined) {
        return this.monthCardInfo.price
      } else {
        return this.monthCardInfo.price * this.discountPrice
      }
    }
  },
  methods: {
    ...mapActions(['cardPaymentInit']),

    // 计算总价
    getTotalMoney: function () {
      if (this.onceCardInfo.price === undefined || this.onceCardInfo.price === '') {
        this.totalMoney = 2
      } else {
        this.totalMoney = this.number * this.onceCardInfo.price
      }
    },
    // 执行购买操作

    // jssdk授权
    weixinConfig: function () {
      var weixinUrl = location.href.split('#')[0]
      this.$http.get(this.$store.state.jssdk, {params: {url: weixinUrl}}).then((res) => {
        var data = res.data
        this.$wechat.config({
          debug: false,
          appId: data.appId,
          timestamp: data.timestamp,
          nonceStr: data.nonceStr,
          signature: data.signature,
          jsApiList: ['chooseWXPay']
        })
      }).catch((error) => {
        console.log(error.response)
      })
    },

    payment: function () {
      this.$vux.loading.show({text: '加载中...'})
      // this.workTypeId
      // 月卡
      console.log('选择的卡类型：' + this.cardTypeId)
      console.log('选择的工种：' + this.workTypeId)
      if (this.cardTypeId === this.monthCardInfo.cardType) {
        console.log('执行购买月卡操作')
        this.$http({
          url: this.$store.state.vxUsercardBuyMonthCard,
          method: 'post',
          params: {openId: this.$store.state.openId},
          data: {
            'count': 1,
            'workType': this.workTypeId
          }
        }).then((res) => {
          if (res.data.code === 0) {
            console.log('vxUsercardBuyMonthCard返回结果：')
            console.log(res)
            console.log('vxUsercardBuyMonthCard调用支付')
            console.log('开始调用wxpay')
            this.wxPay(res.data.userConsume, '用户购卡/月卡', 'userCard', -1, () => {
              // 支付成功后的回调，是到做题界面
              this.$router.push({name: 'GetExercises', params: { workid: this.workTypeId }})
            })
            console.log('结束调用wxpay')
          }
        }).catch((error) => {
          console.log('vxUsercardBuyMonthCard返回错误')
          console.log(error)
        })
      }
      // 次卡
      if (this.cardTypeId === this.onceCardInfo.cardType) {
        console.log('执行购买次卡操作')
        this.$http({
          url: this.$store.state.vxUsercardBuySingleCard,
          method: 'post',
          params: {openId: this.$store.state.openId},
          data: {
            'count': this.number,
            'workType': this.workTypeId
          }
        }).then((res) => {
          console.log('vxUsercardBuySingleCard购卡返回成功,开始调用支付')
          console.log(res)
          this.wxPay(res.data.userConsume, '用户购卡/次卡', 'singleCard', this.number, () => {
            // 支付成功后的回调，是到做题界面
            this.$router.push({name: 'GetExercises', params: { workid: this.workTypeId }})
          })
        }).catch((error) => {
          console.log('vxUsercardBuySingleCard返回错误')
          console.log(error)
        })
      }
    },

    // json:用户消费数据
    // serviceName: 用户购卡(月卡/次卡)
    // serviceType: userCard
    // serviceCount: -1
    // cbSuccess: 执行成功后的要执行的函数
    // cbFailed: 执行失败后的要执行的函数
    // cbCancel: 用户取消后的要执行的函数
    wxPay: function (json, serviceName, serviceType, serviceCount, cbSuccess, cbFailed, cbCancel) {
      // 测试时修改为自己的openId 如果不修改会出现【下单账号与支付账号不一致】的提示 这里最好授权获取
      this.$vux.loading.hide()
      // 测试为1分钱
      // var totalFee = 0.01

      var totalFee = 15
      if (serviceCount === -1) {
        // 月卡
        totalFee = parseFloat(this.monthRealPrice)
      } else {
        // 次卡
        totalFee = parseFloat(this.totalMoney)
      }

      console.log('调用wxPay开始')

      var openId = this.$store.state.openId
      var serviceId = json.id
      var postData = {
        openId: openId,
        total_fee: totalFee,
        serviceSerialNo: json.serialNo,
        serviceName: serviceName,
        serviceId: json.id,
        serviceType: serviceType,
        serviceCount: serviceCount
      }
      console.log('开始调用wxpay的支付操作，post方法')
      console.log(postData)
      this.$http({
        url: this.$store.state.vxApiPay,
        method: 'post',
        params: postData}).then((res) => {
          if (res.data.code === 0) {
            console.log('开始调用微信接口，返回结果如下：')
            console.log(res)
            var data = JSON.parse(res.data.data)
            console.log('JSON转换的结果如下：')
            console.log(data)
            this.weixinConfig()
            this.$wechat.ready(() => {
              this.onBridgeReady(data, serviceId, serviceType, cbSuccess, cbFailed, cbCancel)
            })
          } else {
            if (res.data.code === 2) {
              this.$vux.alert.show({
                title: '发生错误',
                content: res.data.message
              })
            } else {
              console.log(res)
            }
          }
        }).catch((error) => {
          console.log(error.response)
        })
    },
    // json:用户消费数据
    // serviceId: 用户购卡(月卡/次卡)
    // serviceType: userCard
    // cbSuccess: 执行成功后的要执行的函数
    // cbFailed: 执行失败后的要执行的函数
    // cbCancel: 用户取消后的要执行的函数
    onBridgeReady: function (json, serviceId, serviceType, cbSuccess, cbFailed, cbCancel) {
      console.log('onBridgeReady start')
      console.log(json)
      this.$wechat.chooseWXPay({
        // appId: 'wx7919b5009c7935d2',
        timestamp: json.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
        nonceStr: json.nonceStr, // 支付签名随机串，不长于 32 位
        package: json.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
        signType: json.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
        paySign: json.paySign, // 支付签名
        success: function (res) {
                // 支付成功后的回调函数
                // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
          if (res.errMsg === 'chooseWXPay:ok') {
            cbSuccess()
          } else {
            cbFailed()
          }
        },
        cancel: function (res) {
          var cancelUrl = '/vx/orders/payCancel'
          this.$http.get(cancelUrl, {
            openId: this.$store.state.openId,
            serviceId: serviceId,
            serviceType: serviceType
          }, function () {
            cbCancel()
          })
        }
      })
    }

    // method end
  },
  created () {
    // this.$nextTick(function () {
    //   this.cardPaymentInit()
    // })
    this.cardPaymentInit()
  }
}
</script>
<style scoped>
.payButton{
  padding-left:10px;
  padding-right:10px;
  padding-top:10px;
}
.payMsg{
  margin:10px;
  font-size:0.8em;
  color:red;
}
</style>
